<template>
	<view class="container">
		<view class="left-bottom-sign"></view>
		<!-- <view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view> -->
		<view class="right-top-sign"></view>
		<!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
		<view class="wrapper">
			<view class="left-top-sign">LOGIN</view>
			<view class="welcome">欢迎回来！</view>
			<!-- #ifdef MP-WEIXIN -->
			<!-- <button class="confirm-btn" open-type="getUserInfo" @getuserinfo="wxGetUserInfo" withCredentials="true">微信登录</button> -->
			<button v-if="!isLogin" class="confirm-btn" @click="getUserProfile">授权快捷登录</button>
			<button v-if="isLogin" class="confirm-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号快捷登录</button>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<button class="confirm-btn" open-type="getAuthorize" @getAuthorize="onGetAuthorize" @error="onAuthError" scope='userInfo'>支付宝登录</button>
			<!-- #endif -->
			<!-- #ifdef MP-TOUTIAO -->
			<button v-if="!isLogin" class="confirm-btn"  @click="ttGetUserInfo">抖音登录</button>
			<button v-if="isLogin" class="confirm-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号快捷登录</button>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<button class="confirm-btn" @click="wechatH5Login" :disabled="logining">授权快捷登录</button>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex';
	import Api from '@/common/api';
	import WXBizDataCrypt from '@/common/WXBizDataCrypt';
	import store from '@/store/index';
	export default {
		data() {
			return {
				loginType: '',
				logining: false,
				fromMemberId: null,
				sessionKey: '',
				isLogin: false,
				appId: ''
			};
		},
		onLoad() {},
		computed: {
			...mapState(['hasLogin', 'userInfo'])
		},
		methods: {
			...mapMutations(['login']),
			navBack() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			getPhoneNumber(e) {  
				console.log(e.detail.errMsg);  
				console.log(e.detail.iv);  
				console.log(e.detail.encryptedData);
				let errMsg = e.detail.errMsg;
				if(errMsg == "getPhoneNumber:ok"){
					let iv = e.detail.iv;
					let encryptedData = e.detail.encryptedData;
					let pc = new WXBizDataCrypt(this.appId,this.sessionKey);
					let data = pc.decryptData(encryptedData , iv);  
					console.log(data)
					uni.showModal({
						content: '登录成功',
						showCancel: false
					});
					let params = {
						phone: data.phoneNumber
					};
					let result = Api.apiCall('post', Api.member.updateMemberPhone, params);
					if(result){
						let redirectPageUrl = uni.getStorageSync("redirect_page");
						if(undefined != redirectPageUrl && null != redirectPageUrl && "" != redirectPageUrl){
							uni.switchTab({
							    url: redirectPageUrl
							})
						}else{
							if(this.userInfo.userInfo.nickname == '微信用户'){
								uni.redirectTo({
									url: '/pages/public/uploadnickimg'
								});
							}else{
								uni.switchTab({
									url: '/pages/index/index'
								});	
							}	
						}
					}
				}else{
					uni.showModal({
						content: '获取手机号失败，请再次尝试!',
						showCancel: false
					})
				}
			},
			getUserProfile(){
				const that = this;
				let currentStoreId = Api.STORE_ID;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						uni.showModal({
							title: '温馨提示',
							content: '亲，授权微信登录后才能正常使用小程序功能',
							success(res) {
								console.log(res)
								//如果用户点击了确定按钮
								if (res.confirm) {
									uni.getUserProfile({
										desc: '登录',
										success: async (res) => {
										// 后端接口
											console.log(res);
											wx.request({
												url: Api.BASEURI + Api.index.appletLogin_by_weixin,
												data: {
													code: loginRes.code,
													userInfo: res.rawData,
													cloudID: 1000,
													encrypted_data: res.encryptedData,
													iv: res.iv,
													source: 2,
													signature: res.signature,
													storeId: currentStoreId
												},
												method: 'post',
												success: function(info) {
													console.log("登录返回信息" + JSON.stringify(info.data.data));
													that.login(info.data.data);
													let fid = uni.getStorageSync("fromMemberId");
													if (undefined != fid && null != fid && "" != fid) {
														that.fromMemberId = fid;
													}
													if (null != that.fromMemberId) {
														let logparams = {
															logs: "绑定会员关系" + info,
															fromMemberId: that.fromMemberId,
														};
														let result = Api.apiCall('get', Api.index.logs, logparams);
													}
													that.sessionKey = info.data.data.sessionKey;
													that.appId = info.data.data.appId;
													if(info.data.data.userInfo.phone == ""){
														that.isLogin = true;
													}else{
														let redirectPageUrl = uni.getStorageSync("redirect_page");
														console.log('1111111'+redirectPageUrl)
														if(undefined != redirectPageUrl && null != redirectPageUrl && "" != redirectPageUrl){
															if(redirectPageUrl.indexOf('bargain')>0 || redirectPageUrl.indexOf('hongbao')>0){
																uni.redirectTo({
																	url: redirectPageUrl
																})
															}
															uni.switchTab({
																url: redirectPageUrl
															})
														}else{
															if(info.data.data.userInfo.nickname == "微信用户"){
																uni.redirectTo({
																	url: '/pages/public/uploadnickimg'
																});
															}else{
																uni.switchTab({
																	url: '/pages/meallist/selectRoom'
																});	
															}
														}
													}
												},
												fail: function(e) {
													console.log("微信登录失败.");
												}
											});
										},
										fail: (res) => {
											console.log(res)
										}
									});
								} else if (res.cancel) {
									//如果用户点击了取消按钮
									console.log(3);
									uni.showToast({
										title: '您拒绝了请求,不能正常使用小程序',
										icon: 'error',
										duration: 2000
									});
									return;
								}
							}
						});
					}
				});
			},
			wxGetUserInfo: function(res) {
				if (!res.detail.iv) {
					uni.showToast({
						title: '您取消了授权,登录失败',
						icon: 'none'
					});
					return false;
				}
				const that = this;
				let currentStoreId = Api.STORE_ID;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						wx.request({
							url: Api.BASEURI + Api.index.appletLogin_by_weixin,
							data: {
								code: loginRes.code,
								userInfo: res.detail.rawData,
								cloudID: res.detail.cloudID,
								encrypted_data: res.detail.encryptedData,
								iv: res.detail.iv,
								source: 2,
								signature: res.detail.signature,
								storeId: currentStoreId
							},
							method: 'post',
							success: function(info) {
								console.log("登录返回信息" + info.data.data);
								that.login(info.data.data);
								let fid = uni.getStorageSync("fromMemberId");
								if (undefined != fid && null != fid && "" != fid) {
									that.fromMemberId = fid;
								}
								if (null != that.fromMemberId) {
									let logparams = {
										logs: "绑定会员关系" + info,
										fromMemberId: that.fromMemberId,
									};
									let result = Api.apiCall('get', Api.index.logs, logparams);
								}
								uni.switchTab({
									url: '/pages/index/index'
								});
							},
							fail: function(e) {
								console.log("微信登录失败.");
							}
						});
					}
				});
			},
			ttGetUserInfo:function(){
				console.log("抖音登录");
				let that = this;
				tt.login({
				  force: true,
				  success(res) {
				    console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
					// tt.getUserInfo({
					//   withCredentials: true,
					//   success(res) {
					//     console.log(`getUserInfo 调用成功 ${res.userInfo}`);
					//   },
					//   fail(res) {
					//     console.log(`getUserInfo 调用失败`);
					//   },
					// });
					let task = tt.request({
					  url: Api.BASEURI + Api.index.appletLogin_by_toutiao + '/' + res.code,
					  data: {
						  "storeId":Api.STORE_ID
					  },
					  header: {
					    "content-type": "application/x-www-form-urlencoded",
					  },
					  method: "POST",
					  dataType: "JSON", // 指定返回数据的类型为 json
					  success(res) {
						let result = JSON.parse(res.data);
						that.login(result.data);
						that.sessionKey = result.data.sessionKey;
						that.appId = result.data.appId;
						console.log("调用成功", result.data.sessionKey);
						console.log("调用成功", result.data.appId);
						if(result.data.userInfo.phone == ""){
							that.isLogin = true;
						}else{
							uni.switchTab({
								url: '/pages/index/index'
							});
						}
					  },
					  fail(res) {
					    console.log("调用失败", res.errMsg);
					  },
					});
				  },
				  fail(res) {
				    console.log(`login 调用失败`);
				  },
				});
			},
			onGetAuthorize: function(res) {
				my.getOpenUserInfo({
					fail: (res) => {},
					success: (res) => {
						console.log(JSON.parse(res.response).response);
						let userInfo = JSON.parse(res.response).response // 以下方的报文格式解析两层 response
						this.getAuthCode(userInfo);
					}
				});
			},
			wechatH5Login() {
				const that = this
				let href = window.location.origin;
				let page = that.$core.prePage()
			    let fromMemberId = uni.getStorageSync("fromMemberId");
			     console.log(fromMemberId);
				let prePath = "";
				if (undefined != fromMemberId) {
					prePath = '/pages/index/index?memberId=' + fromMemberId
				} else {
					prePath = '/pages/index/index';
				}
				// if (page) {
				// 	prePath = page.__page__.path
				// }
				console.log("前一个页面路径" + prePath);
				window.location = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
					'appid=' + that.$config.dev.h5Appid + '&redirect_uri=' + escape(href) +
					'&response_type=code&connect_redirect=1&scope=snsapi_userinfo&state=' + escape(prePath) + '#wechat_redirect'
			},
			getAuthCode(aliUserInfo) {
				let that = this;
				//let currentStoreId = uni.getStorageSync("currentStoreId");
				my.getAuthCode({
					scopes: 'auth_base', // 主动授权：auth_user，静默授权：auth_base。或者其它scope
					success: (res) => {
						console.log(res.authCode);
						if (res.authCode) {
							// 认证成功
							// 调用自己的服务端接口，让服务端进行后端的授权认证，并且利用session，需要解决跨域问题
							my.request({
								url: Api.BASEURI + 'applet/loginByAliPay/' + res.authCode, // 该url是您自己的服务地址，实现的功能是服务端拿到authcode去开放平台进行token验证
								data: {
									userInfo: aliUserInfo,
									storeId: Api.STORE_ID
								},
								method: "POST",
								success: (info) => {
									// 授权成功并且服务器端登录成功
									console.log("登录返回信息" + info.data.data);
									that.login(info.data.data);
									let fid = uni.getStorageSync("fromMemberId");
									if (undefined != fid && null != fid) {
										that.fromMemberId = fid;
									}
									let logparams = {
										logs: "绑定会员关系" + info,
										fromMemberId: that.fromMemberId,
									};
									Api.apiCall('get', Api.index.logs, logparams);
									uni.switchTab({
										url: '/pages/index/index'
									});
								},
								fail: (e) => {
									// 根据自己的业务场景来进行错误处理
									console.log(e);
								},
							});
						}
					},
				});
			}
		}
	};
</script>

<style lang="scss">
	page {
		background: #fff;
	}

	.container {
		padding-top: 115px;
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background: #fff;
	}

	.wrapper {
		position: relative;
		z-index: 90;
		background: #fff;
		padding-bottom: 40upx;
	}

	.back-btn {
		position: absolute;
		left: 40upx;
		z-index: 9999;
		padding-top: var(--status-bar-height);
		top: 40upx;
		font-size: 40upx;
		color: $font-color-dark;
	}

	.left-top-sign {
		font-size: 120upx;
		color: $page-color-base;
		position: relative;
		left: -16upx;
	}

	.right-top-sign {
		position: absolute;
		top: 80upx;
		right: -30upx;
		z-index: 95;

		&:before,
		&:after {
			display: block;
			content: '';
			width: 400upx;
			height: 80upx;
			background: #b4f3e2;
		}

		&:before {
			transform: rotate(50deg);
			border-radius: 0 50px 0 0;
		}

		&:after {
			position: absolute;
			right: -198upx;
			top: 0;
			transform: rotate(-50deg);
			border-radius: 50px 0 0 0;
			/* background: pink; */
		}
	}

	.left-bottom-sign {
		position: absolute;
		left: -270upx;
		bottom: -320upx;
		border: 100upx solid #d0d1fd;
		border-radius: 50%;
		padding: 180upx;
	}

	.welcome {
		position: relative;
		left: 50upx;
		top: -90upx;
		font-size: 46upx;
		color: #555;
		text-shadow: 1px 0px 1px rgba(0, 0, 0, 0.3);
	}

	.input-content {
		padding: 0 60upx;
	}

	.input-item {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: center;
		padding: 0 30upx;
		background: $page-color-light;
		height: 120upx;
		border-radius: 4px;
		margin-bottom: 50upx;

		&:last-child {
			margin-bottom: 0;
		}

		.tit {
			height: 50upx;
			line-height: 56upx;
			font-size: $font-sm + 2upx;
			color: $font-color-base;
		}

		input {
			height: 60upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			width: 100%;
		}
	}

	.confirm-btn {
		width: 630upx;
		height: 76upx;
		line-height: 76upx;
		border-radius: 50px;
		margin-top: 70upx;
		/* #ifdef MP-ALIPAY*/
		margin-left: 60upx;
		/* #endif */
		background: linear-gradient(to right, #e68d0f, #e61a0f);
		color: #fff;
		font-size: $font-lg;

		&:after {
			border-radius: 100px;
		}
	}

	.forget-section {
		font-size: $font-sm + 2upx;
		color: $font-color-spec;
		text-align: center;
		margin-top: 40upx;
	}

	.register-section {
		position: absolute;
		left: 0;
		bottom: 50upx;
		width: 100%;
		font-size: $font-sm + 2upx;
		color: $font-color-base;
		text-align: center;

		text {
			color: $font-color-spec;
			margin-left: 10upx;
		}
	}
</style>
